import json

from flask import request
from flask import Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import User
import uuid
from flask_jwt_extended import create_access_token, create_refresh_token, get_jwt_identity, jwt_required, get_jwt
from utils.h_result import HResult
from utils.response_handler import handle_response_decorator


bp = Blueprint('account', __name__, url_prefix='/account/')

blacklist = set()


def check_if_token_in_blacklist():
    token = get_jwt()
    jti = token['jti']
    return jti in blacklist  # 检查token是否在黑名单中


class Login(Resource):

    def post(self):
        data = request.get_json()
        name = data.get('name')
        pass_ = data.get('pass')

        if not name or not pass_:
            return HResult().get_result('error', '参数错误!')

        print('name=' + name + ' pass=' + pass_)
        user = User.query.filter_by(name=name).first()
        if user:
            print('pass: ' + user.password)
            if user.validate_password(password=pass_):
                # 身份验证逻辑，验证成功后生成访问令牌和刷新令牌
                access_token = create_access_token(identity=user.name)
                refresh_token = create_refresh_token(identity=user.name)
                return HResult().get_result('success', '登录成功!', {'access_token': access_token, 'refresh_token': refresh_token, 'name': user.name})
            else:
                return HResult().get_result('unauthorized', '密码错误!', {
                    'name': user.name
                })
            pass
        else:
            return HResult().get_result('unauthorized', '账号不存在!')


class Logout(Resource):
    method_decorators = [jwt_required()]

    def get(self):
        # 获取当前用户身份标识
        token = get_jwt()
        blacklist.add(token['jti'])
        return HResult().get_result('success', '退出成功!')


class Refresh(Resource):
    method_decorators = [jwt_required(refresh=True)]  # 使用刷新令牌进行身份验证

    def get(self):
        if check_if_token_in_blacklist():
            return HResult().get_result('unauthorized', '登录失败!')
        # 获取当前用户身份标识
        current_user = get_jwt_identity()
        # 刷新访问令牌
        new_access_token = create_access_token(identity=current_user)
        return HResult().get_result('success', '刷新成功!', {'access_token': new_access_token})


class AddUser(Resource):
    # method_decorators = [jwt_required()]

    def post(self):
        data = request.get_json()

        name = data.get('name')
        password = data.get('pass')

        # 校验入参
        if not name or not password:
            return HResult().get_result('error', '参数错误!')

        # 对name唯一性校验
        if User.query.filter_by(name=name).first():
            return HResult().get_result('unauthorized', '用户已存在!')

        user = User(name=name, pass_word=password, id=str(uuid.uuid4()))
        for column in User.__table__.columns:
            # 包含在data中但不能为name或者pass
            if column.name in data and column.name != 'name' and column.name != 'pass':
                setattr(user, column.name, data[column.name])
        # user对象会自动加密密码
        db.session.add(user)
        db.session.commit()
        return HResult().get_result('success', '注册成功!', user.to_dict())


class DeleteUser(Resource):
    method_decorators = [jwt_required()]

    def post(self):
        data = request.get_json()
        user_ids = data['ids']
        for user_id in user_ids:
            user = User.query.filter_by(id=user_id).first()
            if user:
                db.session.delete(user)
        db.session.commit()
        return HResult().get_result('success', '删除成功!')


class UpdateUser(Resource):
    method_decorators = [jwt_required()]

    def post(self):
        # 修改用户信息
        data = request.get_json()
        user_id = data['id']
        user_data = data['user']
        user = User.query.filter_by(id=user_id).first()
        # 遍历user，获取需要修改的字段并修改
        for key, value in user_data.items():
            if key == 'id':
                continue
            setattr(user, key, value)
        db.session.commit()
        return HResult().get_result('success', '修改成功!')


class UserInfo(Resource):
    method_decorators = [jwt_required()]

    def get(self):
        name = request.args.get('name')
        id = request.args.get('id')
        if name:
            user = User.query.filter_by(name=name).first()
        elif id:
            user = User.query.filter_by(id=id).first()
        else:
            return HResult().get_result('error', '没有这个用户')
        if user:
            return HResult().get_result('success', data=user.to_dict())


class QueryAllUser(Resource):
    method_decorators = [jwt_required()]

    def get(self):
        users = User.query.all()
        return HResult().get_result('1', data=[user.to_dict() for user in users])


api = Api(bp)
api.add_resource(Login, '/login/', endpoint='login')
api.add_resource(Refresh, '/refresh/', endpoint='refresh')
api.add_resource(AddUser, '/add/', endpoint='add')
api.add_resource(DeleteUser, '/delete/', endpoint='delete')
api.add_resource(UpdateUser, '/update/', endpoint='update')
api.add_resource(UserInfo, '/queryUserInfo/', endpoint='userInfo')
api.add_resource(QueryAllUser, '/queryAll/', endpoint='queryAllUser')
